<?php

namespace apiend\models;

use Yii;
use common\base\Model;
use apiend\models\User;
use common\logics\captcha\SmsForm;

/**
 * 短信登录
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class SmsLoginForm extends Model {

    public $mobile;
    public $captcha;
    public $token = null;
    //
    private $_user = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            // username and password are both required
            [['mobile', 'captcha'], 'required'],
            // password is validated by validatePassword()
            ['mobile', 'validateUser'],
            ['captcha', 'validateCaptcha'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateUser($attribute) {
        if (!$this->hasErrors()) {
            if (!$this->getUser()) {
                $this->addError($attribute, '输入的手机号信息不存在');
            }
        }
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateCaptcha($attribute) {
        if (!$this->hasErrors()) {
            $captcha = Yii::$app->cache->get('captcha_' . SmsForm::SCOPE_LOGIN . '_' . $this->mobile);
            if ($captcha == false) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . '已过期');
            } elseif ($captcha !== $this->$attribute) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . '不正确');
            }
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findByMobile($this->mobile);
        }
        return $this->_user;
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login() {
        if (!$this->validate()) {
            $this->dumpError('手机号或短信码输入错误', false);
        }
        Yii::$app->cache->delete('captcha_' . SmsForm::SCOPE_LOGIN . '_' . $this->mobile);
        return $this->getUser()->meta;
    }

}
